// 预算管理弹窗表单
<template>
  <div class="addDialog">
    <el-dialog  :close-on-click-modal="false" :title="dialogTitle" :visible.sync="dialogVisible" width="1200px" @closed="handleClosed">
      <el-form ref="form" :rules="rules" :model="formData">
        <el-row :gutter="40">
          <el-col :span="24">
            <h4 class="mt0">预算信息</h4>
          </el-col>
          <el-col :span="12" class="listFormItem">
            <el-button type="primary" class="add" size="mini" @click="chooseProperty" v-if="type == 'add'">选择物业</el-button>
            <el-form-item label="物业名称" prop="propertyName">
              <el-input v-model="formData.propertyName" readonly placeholder="请输入物业名称"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工程名称" prop="engineeringName">
              <el-input v-model="formData.engineeringName" maxlength="100" :readonly="isReadonly" placeholder="请输入工程名称"/>
            </el-form-item>
          </el-col>
          <el-col :span="24" class="por">
            <h4 class="mt0 mb0">报价情况</h4>
            <el-button type="primary" size="mini" @click="addDepartment" v-if="!isReadonly">添加</el-button>
          </el-col>
        </el-row>

        <el-table ref="multipleTable"  :data="quoteInfoList" class="companyList">
          <el-table-column label="单位名称" align="center">
            <template slot-scope="scope">
              <el-form-item v-if="!isReadonly">
                <el-select
                  v-model="scope.row.unitName"
                  value-key="unitName"
                  filterable
                  remote
                  reserve-keyword
                  placeholder="请输入单位名称"
                  :remote-method="remoteMethod"
                  :loading="loading"
                  @change="handleSelectChange($event, scope.$index)"
                  :disabled="scope.row.readonly"
                  style="width:100%"
                >
                  <el-option
                    v-for="item in list"
                    :key="item.supplierId"
                    :label="item.unitName"
                    :value="item"
                  >{{item.unitName}}</el-option>
                </el-select>
              </el-form-item>
              <span v-else>{{scope.row.unitName}}</span>
            </template>
          </el-table-column>
          <el-table-column label="单位类型" width="200" align="center">
            <template slot-scope="scope">
              <el-form-item v-if="!scope.row.readonly">
                <el-select
                  placeholder="请选择单位类型"
                  v-model="scope.row.unitType"
                  v-if="companyDict.children.length"
                >
                  <el-option
                    :value="item.value.toString()"
										:label="item.label"
                    :key="item.value"
                    v-for="item in companyDict.children"
                  >{{item.label}}</el-option>
                </el-select>
              </el-form-item>
              <span v-else>{{getCompanyName(scope.row.unitType)}}</span>
            </template>
          </el-table-column>
          <el-table-column label="报价" width="200" align="center">
            <template slot-scope="scope">
              <el-form-item v-if="!scope.row.readonly">
                <el-input v-model="scope.row.quotePrice" oninput ="value=value.replace(/[^0-9.]/g,'')" placeholder="请输入报价金额"  maxlength="15"/>
              </el-form-item>
              <span v-else>{{scope.row.quotePrice}}</span>
            </template>
          </el-table-column>
          <el-table-column label="中选" width="150" align="center"  >
            <template slot-scope="scope">
              <el-form-item  v-if="!scope.row.readonly">
                <el-select
                  v-model="scope.row.isChoice"
                  @change="handleChoiceChange(scope.$index)">
                  <el-option
                    :value="item.value"
                    v-for="item in choiceList"
                    :key="item.value"
                    :label="item.label"
                  />
                </el-select>
              </el-form-item>
              <span v-else>{{scope.row.isChoice == '10' ?'中选':'不中选'}}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="130" v-if="!isReadonly" align="center">
            <template slot-scope="scope">
              <el-button type="text" size="mini" v-if="!scope.row.readonly" @click="removeItem(scope.$index)">移除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <el-row :gutter="40">
          <el-col :span="24">
            <h4 class="dialogItemTitle">送审情况</h4>
          </el-col>
          <el-col :span="12">
            <el-form-item label="送审日期" prop="censorshipDate" class="dateChoose">

              <el-date-picker
                v-model="formData.censorshipDate"
                value-format="yyyy-MM-dd HH:mm:ss"
                type="datetime"
                placeholder="请输入送审日期"
                :readonly="isReadonly"
                style="width:100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="送审金额" prop="censorshipAmount" class="full">
              <el-input maxlength="15" oninput="value=value.replace(/[^\d.]/g,'')" v-model="formData.censorshipAmount" :readonly="isReadonly" placeholder="请输入送审金额"/>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="核减金额" prop="reductionAmount" class="full">
              <el-input v-model="formData.reductionAmount" oninput="value = value.replace(/[^0-9.]/g,'')" :readonly="isReadonly" maxlength="15" placeholder="请输入核减金额"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="审定金额" class="full">
              <el-input
                v-model="formData.approvalAmount"
                disabled
                placeholder="请输入审定金额"
                maxlength="15"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <!-- 物业选择弹窗 -->
      <propertyChooseDialog
        ref="propertyChoose"
        dialogType="budget"
        @changeProperty="handlePropertyChange"
      />
      <div slot="footer">
        <el-button @click="dialogVisible = false">关闭</el-button>
        <el-button  v-if="type !== 'preview'" type="primary" v-throttle="[save]">提 交</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import propertyChooseDialog from "@/views/wy-operate/components/propertyChooseDialog";
import {
  changeBudgetInfo,
  getQuoteList,
  getDePartment,
} from "@/views/wy-operate/api/repair.js";
import { mapState } from "vuex";
export default {
  name: "addDepartment",
  components: {
    propertyChooseDialog,
  },
  inject: ['initList'],
  data() {
    var validateMinus = (rule, value, callback) => {
      callback(parseFloat(value) > this.formData.censorshipAmount ? new Error('核减金额不能超过送审金额') : '');
    };
    return {
      type: "add", //弹窗类型，默认新增
      //弹窗开关
      dialogVisible: false,
      // 表单项
      formData: {
        operateName: "",
        billId: [],
        engineeringName: "",
        censorshipDate: "",
        censorshipAmount: "",
        approvalAmount: "",
        reductionAmount: "",
        roomId: ''
      },
      // 报价信息
      quoteInfoList: [],
      // 校验规则
      rules: {
        propertyName: [{required: true, message: '物业名称不能为空', trigger: 'blur'}],
        engineeringName: [{required: true, message: '工程名称不能为空', trigger: 'blur'},
            { min: 1, max: 25, message: '长度在 1 到 25 个字符', trigger: 'blur' }],
        censorshipDate: [{required: true, message: '送审日期不能为空', trigger: 'blur'}],
        censorshipAmount: [
          {required: true, message: '送审金额不能为空', trigger: 'blur'},
          { pattern: /(^(([1-9]+\d*)|(0{1}))(.\d{1,2})?)|(^-([1-9]+\d*(\.\d{1,2})?|0\.(0[1-9]{1}|[1-9]{1}\d?)))/, message: "请输入正确的金额", trigger: "blur" },
        ],
        reductionAmount: [
          { pattern:  /(^(([1-9]+\d*)|(0{1}))(.\d{1,2})?)|(^-([1-9]+\d*(\.\d{1,2})?|0\.(0[1-9]{1}|[1-9]{1}\d?)))/, message: "请输入正确的金额", trigger: "blur" },
          { validator: validateMinus, trigger: "blur" },
        ],
      },
      // 中选设置
      choiceList: [
        { label: "中选", value: "10" },
        { label: "不中选", value: "11" },
      ],
      // 公司名称列表
      list: [],
      loading: false,
      // 选中的单位
      chooseUnit: {},
    };
  },
  computed: {
    ...mapState({
      // 公司类型列表
      companyDict: (state) =>
        state.dict.find((item) => item.type === "provider_type") || {
          children: [],
        },
    }),
    // 弹窗标题计算
    dialogTitle() {
      return {
        preview: "查看",
        edit: "编辑",
        add: "新增",
      }[this.type];
    },
    // 是否只读
    isReadonly() {
      return this.type == "preview";
    },
  },
  watch: {
    formData: {
      deep: true,
      handler(val){
        if(this.type !== 'preview') {
          this.formData.approvalAmount = (parseFloat(this.formData.censorshipAmount || 0) - parseFloat(this.formData.reductionAmount || 0)).toFixed(2)
        }
      }
    }
  },
  methods: {
    //开启弹窗
    async show({ type, data = {} }) {
      this.dialogVisible = true;
      this.type = type;
      if (["preview", "edit"].includes(type)) {
        this.formData = data;
        // 获取报价列表
        const res = await getQuoteList(data.obtId);
        // 判断没有报价的情况
        if (res.data.data.length && res.data.data[0].quoteInfo) {
          this.quoteInfoList = res.data.data.map((item) => {
            return {
              ...item.quoteInfo,
              readonly: true,
            };
          });
        }
      }
    },
    // 提交新增
    save() {
      this.$refs.form.validate(async (valid) => {
        if(!valid) return false;
        if(this.quoteInfoListVerify()) {
          let params = {
            billId: this.formData.billId,
            operationBudget: this.formData,
            quoteInfoList: this.quoteInfoList,
          };
          params.operationBudget.reductionAmount = parseFloat(params.operationBudget.reductionAmount)
          changeBudgetInfo(params, this.type).then(res => {
            if(res.data.data.code == 200) {
              this.$message.success(`${this.dialogTitle}成功!`);
              this.dialogVisible = false
              this.initList({current: 1, keyword: ''})
            } else {
              this.$message.error(res.data.msg || res.data.data.msg)
            }
          })
        }
      });
    },
    // 报价情况校验{ pattern: /^\d+(\.\d{1,2})?$/, message: "请输入正确的金额", trigger: "blur" },
    quoteInfoListVerify(){
      if(!this.quoteInfoList.length){
        this.$message.error('报价情况不能为空')
        return false
      } else if (this.quoteInfoList.some(item => item.unitName == undefined || item.unitName == '')){
        this.$message.error('单位名称不能为空')
        return false
      } else if (this.quoteInfoList.some(item => item.unitType == undefined || item.unitType == '')){
        this.$message.error('单位类型不能为空')
        return false
      } else if (this.quoteInfoList.some(item => item.quotePrice == undefined || item.quotePrice == '')){
        this.$message.error('报价金额不能为空')
        return false
      } else if (this.quoteInfoList.some(item => !/^\d+(\.\d{1,2})?$/.test(item.quotePrice))){
        this.$message.error('请填写正确报价金额')
        return false
      } else if (this.judgeCheckNumber(this.quoteInfoList)){
        this.$message.error('中选单位最多只能有一个')
        return false
      } else {
        return true
      }
    },
    // 判断是否有多个中选的报价
    judgeCheckNumber(list){
      let choosed = 0
      list.forEach(item => {
        item.isChoice == '10' && choosed++
      });
      return choosed > 1
    },
    // 选择物业名称
    chooseProperty() {
      this.$refs.propertyChoose.show();
    },
    // 监听物业改变
    handlePropertyChange(data) {
      //console.log(data)
      this.formData = {
        ...this.formData,
        propertyName: data.propertyName,
        billId: [data.billId],
        roomId: data.roomId
      }
    },
    // 新增单位
    addDepartment() {
      this.quoteInfoList.push({
        supplierId: "",
        clientProviderName: "",
        clientProviderType: "",
        isChoice: "11", //10中选，11不中选
      });
    },
    // 移除报价
    removeItem(index) {
      this.quoteInfoList.splice(index,1)
    },
    // 监听选中修改
    handleChoiceChange(value, index) {
      if(value == '10') {
        for (let i = 0; i < this.quoteInfoList.length; i++) {
          if(index != i) {
            this.quoteInfoList[i].isChoice = "11";
          }
        }
      }
    },
    // 弹窗关闭回调
    handleClosed() {
      this.formData = {};
      this.quoteInfoList.length = 0;
      this.list.length = 0
    },
    // 工程名称模糊查询
    async remoteMethod(query) {
      if (!this.loading) {
        this.loading = true;
        const res = await getDePartment({
          size: 20,
          current: 1,
          clientProviderName: query,
        });
        this.list = res.data.data.records.map((item) => {
          const { supplierId, clientProviderName, clientProviderType } = item;
          return {
            supplierId,
            unitName: clientProviderName,
            unitType: clientProviderType
          };
        });
        this.loading = false;
      }
    },
    //  单位选择监听
    handleSelectChange(ev,index) {
      console.log(ev)
      //unitType
      this.quoteInfoList[index].supplierId = ev.supplierId
      this.quoteInfoList[index].quoteId = ev.supplierId
      this.quoteInfoList[index].unitName = ev.unitName
      this.quoteInfoList[index].unitType = ev.unitType
    },
    // 获取公司单位类型
    getCompanyName(unitType){
      let companyType = this.companyDict.children.find(item => item.value == unitType)
      return companyType ? companyType.label : ''
    }
  },
};
</script>

<style lang="scss" scoped>
@import "src/views/wy-operate/css/operate.scss";
.por{
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}
.dateChoose{
  /deep/ .el-form-item__label{
    float: none;
  }
}
.companyList .el-form-item{
  margin-bottom: 0;
}

</style>
